package com.google.code.coma.gui.rmi;

import com.google.code.coma.Coma;
import com.google.code.coma.domain.Order;
import com.google.code.coma.domain.Part;
import com.google.code.coma.gui.DataProvider;
import com.google.code.coma.rmi.ObserveCallback;
import com.google.code.coma.rmi.RMIManager;
import com.google.code.coma.rmi.storage.StorageService;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.scene.control.ListView;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.List;

/**
 * @author Dominik Strasser, dominikstr@gmail.com
 */
public class RMIOrderDataProvider extends AbstractRMIDataProvider<Order> implements DataProvider<Order> {
	private static final Log log = LogFactory.getLog(RMIOrderDataProvider.class);

	private ObserveCallback<Order> callback;

    public RMIOrderDataProvider(String factoryId) {
        super(factoryId);
    }

    @Override
	public void bind(final ListView<Order> orderListView) {
		storageService = RMIManager.getStorageService(factoryId + "_" + Coma.ORDER_CONTAINER);
		try {
			callback = new ObserveCallback<Order>() {
				@Override
				public void onChange(ChangeAction changeAction, final List<Order> entries) throws RemoteException {
					Platform.runLater(new Runnable() {
						@Override
						public void run() {
							orderListView.setItems(FXCollections.<Order>observableArrayList(entries));
						}
					});
				}
			};
			storageService.registerObserveCallback((ObserveCallback<Order>) UnicastRemoteObject.exportObject(callback, 0), ObserveCallback.ChangeAction.values());
		} catch (RemoteException e) {
			log.error(e);
		}
	}

	@Override
	public void shutdown() {

	}
}
